<?php
ini_set('display_errors','1');
ini_set('display_startup_errors','1');
error_reporting (E_ALL); 
if ( defined('ABSPATH') )
	include_once ABSPATH . 'config.php';
else
    include_once '../config.php';

include_once ABSPATH."base/cURL.php";
include_once ABSPATH."common/date.php";
include_once ABSPATH."base/rss.php";
include_once ABSPATH."base/people.php";
include_once ABSPATH."base/sig_manager.php";


$id = $_GET["id"];
$address = $_GET["from"];
$last_update = $_GET["last_update"];
$cmd=$_GET["cmd"];

$person = new Person($id);


if($cmd == "connections.get")
{
	$json = '{"connections" : [';
	$contacts = '';
	$rs = $person->ConnectionsGetByFrequency();
	if($rs)
	{
		$connections = $rs;
	}
	$rs = $person->ConnectionsGetByUpdateCheck();
	if($rs)
	{
		$rs = $connections + $rs;
		//Remove duplicates.
		$rs = make_array_unique($rs);
		foreach($rs as $row) {
			if(strlen($contacts) > 0)
			{
				$contacts .= ',';
			}
			$last_update = $row["last_update"];
			$contacts .= '{ "from" : "'.$row["address"].'" , "last_update" : "'.$last_update.'"}';			
		}
	}
	$json .= $contacts .']}';

	echo $json;
}

if($cmd == "posts.get")
{

	//Changing $from to this user's address for outbound communications.
	//Do not confuse it here with an inbound call.
	$from = $person->address;
	
    //Update last_check datetime.
    $contact_id = Person::IDFromAddress($address);
    $person = new Person($contact_id);
    $person->last_check = date("Y-m-d H:i:s");
    $person->Save();
	
	
	$curl = new cURL(FALSE);
	
	$xml = "";
	//Generate the url
	$url = $address."&cmd=feed.personal&from=".urlencode($from)."&last_update=".urlencode($last_update)."&nocache=".urlencode(Date("Y-m-d H:i:s"));

	//Create the signature
	$sig = new Signature($id,$address,$url);
	//Add the signature
	$url .= "&sig=".$sig->signature;
	//Save request for verification
	$sig->Save();

	$xml = $curl->get($url);

	if(isset($_GET['dieurl']))
	{
		die($url);
	}
	
	$dom = new DOMDocument();
	
    $dom->loadXML($xml);
    
    $channels = $dom->getElementsByTagName("channel");
   
    $channel_title = "";  //Screen Name
    $channel_image = "";
    $channel_managingEditor = ""; //Email Address (Name)
    
    foreach($channels as $channel)
    {
        foreach($channel->childNodes as $elems)
        {
            switch ($elems->nodeName)
            {
                case 'title':
                    $channel_title = $elems->nodeValue;
                    break;
                case 'managingEditor':
                    $channel_managingEditor = $elems->nodeValue;
	                break;
                case 'image':
                    $channel_image = $elems->nodeValue;
	                break;
            }
	  }
    }

    $items = $dom->getElementsByTagName("item");
    foreach($items as $item)
    {
    	$title = "";
    	$pubDate = "";
    	$guid = "";
    	$link = "";
    	$description = "";
    	foreach($item->childNodes as $elems)
        {
            switch ($elems->nodeName)
            {
                case 'title':
                    $title = $elems->nodeValue;
                    break;
                case 'guid':
                    $guid = $elems->nodeValue;
                    break;
                case 'pubDate':
                	$offset = substr($elems->nodeValue,26,5);
                    $jDate = new JDate($elems->nodeValue,$offset);
                    $pubDate = $jDate->toMySQL();  
                    if($pubDate > $last_update)
                    {
                    	$last_update = $pubDate;
                    }
	                break;
                case 'link':
                    $link = $elems->nodeValue;
	                break;
                case 'description':
                    $description = $elems->nodeValue;
	                break;	                
            }
	    }
	    
	    //Change back to main user.
	    $person = new Person($id);
		$rs = $person->ChannelsGet($contact_id);
		foreach($rs as $row)
		{
			$channel_id = $row["channel_id"];	    
	    	PostInsert($contact_id, $channel_id, $channel_managingEditor, $channel_title, $channel_image, $pubDate, $link, $description, $guid);
		}
    	
	    //Update last_update datetime.
	    if(isValidDateTime($last_update))
	    {
	   		//echo $last_update;
	   		$person->last_update = $last_update;
    		$person->Save();
	    }
    }
	echo "done";
}

function PostInsert($id, $channel_id, $emailName, $screen_name, $image, $pubDate, $link, $status, $guid) {

	global $db;
	$name = "";
	$email = "";
	
	$emailNameArr = split("\(", $emailName);
	if(count($emailNameArr) > 1)
	{
		$email = trim($emailNameArr[0]);
		$name = $emailNameArr[1];
		$name = trim(str_replace(")","",$name));
	}

	$person = new Person($id);
	if($person->name != $name || $person->email != $email || $person->screen_name != $screen_name || $person->image != $image)
	{
		$person->name = $name;
		$person->screen_name = $screen_name;
		$person->email = $email;
		$person->image = $image;
		$person->Save();
	}
           
	$rs = $db->get_results("select id from $db->posts where channel_id='$channel_id' and permalink='$guid'");

	if(!$rs)
	{
	    //Insert Post	
		$db->query("insert into $db->posts (ownerid, channel_id, status, link, permalink, timestamp) values('$id','$channel_id','".$db->escape($status)."', '".$db->escape($link)."', '".$db->escape($guid)."','".$db->escape($pubDate)."') "
		    ."  ");
	}
}

   
function make_array_unique(&$old){ 
    $new = array(); 
    foreach($old as $key => $value){ 
        if(!in_array($value, $new)) $new[$key] = $value; 
    } 
    return $new; 
} 
?>